package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWmChannelClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vo.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author CC
 * time 2024-06-08
 * description
 */
@Service
@Transactional
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private IWmChannelClient iWmChannelClient;

    @Autowired
    private CacheService cacheService;

    @Override
    public void computedHotArticle() {
        Date date = DateTime.now().minusDays(5).toDate();
        //获取前5天的所有文章
        List<ApArticle> apArticleList = apArticleMapper.findArticlesByLastFiveDays(date);

        //计算文章分值
        List<HotArticleVo> hotArticleVoList = computedHotArticle(apArticleList);
        //3.为每个频道缓存30条分值较高的文章
        cacheTagToRedis(hotArticleVoList);

    }

    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        ResponseResult list = iWmChannelClient.list();
        if (list.getCode()==200) {
            //每个频道缓存30条分值较高的文章
            List<WmChannel> channels = (List<WmChannel>) list.getData();
            if (!CollectionUtils.isEmpty(channels)) {
                for (WmChannel channel : channels) {
                    //获取频道的文章
                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().filter(x -> x.getChannelId().equals(channel.getId()))
                            .collect(Collectors.toList());
                    //取出并缓存30条热度文章
                    sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + channel.getId());
                }
            }
            //设置推荐数据
            sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE+ArticleConstants.DEFAULT_TAG);
        }
    }

    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        List<HotArticleVo> list = hotArticleVos.stream().
                sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).collect(Collectors.toList());
        if (list.size()>30) {
            list=list.subList(0,30);
        }
        cacheService.set(key, JSON.toJSONString(list));
    }

    /**
     * 计算文章分值
     * @param apArticleList
     * @return
     */
    private List<HotArticleVo> computedHotArticle(List<ApArticle> apArticleList) {
        List<HotArticleVo> hotArticleVoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(apArticleList)) {
            for (ApArticle apArticle : apArticleList) {
                HotArticleVo hot = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hot);
                hot.setScore(computedScore(apArticle));
                hotArticleVoList.add(hot);
            }
        }
        return hotArticleVoList;
    }
    /**
     * 计算文章的具体分值
     * @param apArticle
     * @return
     */
    private Integer computedScore(ApArticle apArticle) {
        Integer scere = 0;
        if(apArticle.getLikes() != null){
            scere += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if(apArticle.getViews() != null){
            scere += apArticle.getViews();
        }
        if(apArticle.getComment() != null){
            scere += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if(apArticle.getCollection() != null){
            scere += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return scere;
    }
}
